﻿using Models.Common;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using Web.Common;
using Web.Filters;

namespace Web.Controllers.API
{
    public class DepartmentController : ApiController
    {
        /// <summary>
        /// 添加部门
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult InsertDepartment([FromBody]Models.API.Param.Department entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            
            try
            {
                SqlParameter[] parameters = {
                new SqlParameter("@Parid",SqlDbType.VarChar,50),
                new SqlParameter("@DbName",SqlDbType.VarChar,30),
                new SqlParameter("@UserCode",SqlDbType.VarChar,100),
                new SqlParameter("@FullName",SqlDbType.VarChar,100),
                new SqlParameter("@Name",SqlDbType.VarChar,100),
                new SqlParameter("@Comment",SqlDbType.VarChar,50),
                new SqlParameter("@LinkMan",SqlDbType.VarChar,50),
                new SqlParameter("@Tel",SqlDbType.VarChar,50),
                new SqlParameter("@Fax",SqlDbType.VarChar,50),
                new SqlParameter("@PyCode",SqlDbType.VarChar,200)
                };

                parameters[0].Value = "00000";
                parameters[1].Value = "Department";
                parameters[2].Value = entity.UserCode;
                parameters[3].Value = entity.FullName;
                parameters[4].Value = entity.Name;
                parameters[5].Value = string.IsNullOrWhiteSpace(entity.Comment) ? "" : entity.Comment;
                parameters[6].Value = entity.LinkMan;
                parameters[7].Value = entity.Tel;
                parameters[8].Value = entity.Fax;
                parameters[9].Value = entity.PyCode;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString,"Gp_InsertD", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 修改部门
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult UpdateDepartment([FromBody]Models.API.Param.Department entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }
            
            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                result.Data = "Warning";
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.FullName))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "FullName不可为空";
                result.Data = "Warning";
                return Json(result);
            }
            
            try
            {
                SqlParameter[] parameters = {
                    new SqlParameter("@TypeId",SqlDbType.VarChar,50),
                    new SqlParameter("@UserCode",SqlDbType.VarChar,100),
                    new SqlParameter("@FullName",SqlDbType.VarChar,100),
                    new SqlParameter("@Name",SqlDbType.VarChar,100),
                    new SqlParameter("@Comment",SqlDbType.VarChar,50),
                    new SqlParameter("@LinkMan",SqlDbType.VarChar,50),
                    new SqlParameter("@Tel",SqlDbType.VarChar,50),
                    new SqlParameter("@Fax",SqlDbType.VarChar,50),
                    new SqlParameter("@PyCode",SqlDbType.VarChar,200)
                };

                string strSQL = "select typeid from Department where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                string typeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();

                parameters[0].Value = typeid;
                parameters[1].Value = entity.UserCode;
                parameters[2].Value = entity.FullName;
                parameters[3].Value = entity.Name;
                parameters[4].Value = string.IsNullOrWhiteSpace(entity.Comment) ? "" : entity.Comment;
                parameters[5].Value = entity.LinkMan;
                parameters[6].Value = entity.Tel;
                parameters[7].Value = entity.Fax;
                parameters[8].Value = entity.PyCode;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString,"Gp_UpdateD", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }

        /// <summary>
        /// 删除部门
        /// </summary>
        /// <param name="entity"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult DeleteDepartment([FromBody]Models.API.Param.Department entity)
        {
            Result<string> result = new Result<string>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = "Error";
                result.TotalRows = 0;
                return Json(result);
            }

            if (string.IsNullOrWhiteSpace(entity.UserCode))
            {
                result.Type = AjaxResultType.Warning;
                result.Content = "UserCode不可为空";
                return Json(result);
            }

            try
            {
                SqlParameter[] parameters = {
                new SqlParameter("@typeid",SqlDbType.VarChar,100),
                new SqlParameter("@dbname",SqlDbType.VarChar,100),
                new SqlParameter("@deltype",SqlDbType.Int)
                };

                string strSQL = "select typeid from Department where UserCode =" + FreeADO.DBUtility.DbHelperSQL.StrToSqlStr(entity.UserCode);
                string typeid = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0].Rows[0]["typeid"].ToString();
                
                parameters[0].Value = typeid;
                parameters[1].Value = "Department";
                parameters[2].Value = 0;

                int resultCount = FreeADO.DBUtility.DbHelperSQL.RunProcedure(connectionString,"Gp_StopBaseInfo", parameters, out resultCount);

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.TotalRows = resultCount;
                result.Data = "OK";
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }
        
        /// <summary>
        /// 查询部门
        /// </summary>
        /// <param name="UserCode">部门ID</param>
        /// <param name="Name">名称</param>.
        /// <param name="Delfg">删除标识</param>
        /// <param name="PageIndex">当前页</param>
        /// <param name="PageSize">每页大小</param>
        /// <param name="result"></param>
        /// <returns></returns>
        [HttpPost]
        public IHttpActionResult SelectDepartment(dynamic dyobj)
        {
            dynamic mydyobj = JsonConvert.DeserializeObject(Convert.ToString(dyobj).Trim());

            string strSQL;
            Result <DataTable> result = new Result<DataTable>();

            string connectionString = "";
            string msg = Common.Common.GetHerdeerConnString(this.Request.Headers, out connectionString);
            if (!"OK".Equals(msg))
            {
                result.Type = AjaxResultType.Error;
                result.Content = msg;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }

            try
            {
                strSQL = "";
                strSQL += "select ";
                //strSQL += " typeid ";
                strSQL += "  parid ";
                strSQL += " ,leveal ";
                strSQL += " ,usercode ";
                strSQL += " ,FullName ";
                strSQL += " ,Name ";
                strSQL += " ,Comment ";
                strSQL += " ,deleted ";
                strSQL += " ,Tel ";
                strSQL += " ,Fax ";
                strSQL += " ,LinkMan ";
                strSQL += " ,PyCode ";
                strSQL += " from Department ";
                strSQL += " where 1=1 ";

                string sqlstrcount = "";
                sqlstrcount += "select count(*) from Department where 1=1 ";

                if (null != mydyobj.UserCode && !string.IsNullOrWhiteSpace(mydyobj.UserCode.ToString())) {
                    strSQL += " and usercode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
                    sqlstrcount += " and usercode = N'" + mydyobj.UserCode.ToString().Replace("'", "''") + "'";
                }
                if (null != mydyobj.Name && !string.IsNullOrWhiteSpace(mydyobj.Name.ToString())) { 
                    strSQL += " and (FullName like '%" + mydyobj.Name.ToString() + "%' or Name like '%" + mydyobj.Name.ToString() + "%')";
                    sqlstrcount += " and (FullName like '%" + mydyobj.Name.ToString() + "%' or Name like '%" + mydyobj.Name.ToString() + "%')";
                }
                if (null != mydyobj.Delfg && "0".Equals(mydyobj.Delfg.ToString())) { 
                    strSQL += " and deleted = '0'";
                    sqlstrcount += " and deleted = '0'";
                }

                strSQL += " order by typeid asc ";
                
                if (!"0".Equals(mydyobj.PageIndex.ToString()) && !"0".Equals(mydyobj.PageSize.ToString()))
                {
                    strSQL += " offset " + (Convert.ToInt32(mydyobj.PageIndex.ToString()) - 1) * Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows fetch next " + Convert.ToInt32(mydyobj.PageSize.ToString())
                    + " rows only";
                }

                result.TotalRows = Convert.ToInt32(new FreeADO.DBUtility.DbHelperSQLP(connectionString).GetSingle(sqlstrcount));
                DataTable dt = FreeADO.DBUtility.DbHelperSQL.Query(connectionString, strSQL).Tables[0];

                result.Type = AjaxResultType.Success;
                result.Content = "成功";
                result.Data = dt;
              //  result.TotalRows = dt.Rows.Count;
            }
            catch (Exception ex)
            {
                result.Type = AjaxResultType.Error;
                result.Content = ex.Message;
                result.Data = null;
                result.TotalRows = 0;
                return Json(result);
            }
            return Json(result);
        }



    }
}